package com.tzu.ft.transfer.client;

import com.tzu.ft.base.FTConst;
import com.tzu.ft.base.ResultParam;
import com.tzu.ft.base.SendParam;
import com.tzu.ft.base.TransferTools;
import com.tzu.ft.transfer.ClientFactory;
import com.tzu.ft.transfer.ClientUI;
import com.tzu.utils.JSONTools;
import com.tzu.ssl.KeyInfo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

public abstract class Client {

	protected Socket socket;
	protected String host;
	protected int port;
	protected ClientUI ui;

	/**
	 * 初始化
	 */
	public abstract void init(String host, int port, KeyInfo keyInfo, ClientUI ui) throws Exception;

	/**
	 * 通过ssl socket与服务端进行连接,并且发送一个消息
	 */
	public void send() throws Exception {
		File file = ui.getFile();
		// 拼装发送参数
		SendParam param = ui.getSendParam();
		String msg = JSONTools.toJSONString(param);

		// 封装处理流对象
		DataInputStream dataInputStream = TransferTools.getDataInputStream(socket.getInputStream());
		DataOutputStream dataOutputStream = TransferTools.getDataOutputStream(socket.getOutputStream());

		// 发送信息
		TransferTools.sendInfo(dataOutputStream, msg);
		// 接收反馈
		ResultParam resultParam = TransferTools.readInfo(dataInputStream, ResultParam.class);
		// 发送文件
		switch (resultParam.getCode()) {
		case FTConst.FT_STATUS_CODE_100:
		case FTConst.FT_STATUS_CODE_101:
			System.out.println("发送文件：" + file.getName());
			TransferTools.sendFile(dataOutputStream, file, resultParam.getStartLength(), ui);
			dataOutputStream.close();
			break;
		default:

		}
		dataInputStream.close();
		close();
		// ui交互完成
		ui.finish(1, "传输完成");
	}

	public void stop() {

	}

	public void exit() throws Exception {
		close();
		ui.finish(0, "强制结束");
	}

	protected void close() throws IOException {
		socket.close();
		ClientFactory.getClientMap().remove(hashCode() + "");
	}

}
